<template>
  <view class="vehicle-list-page page-content">
    <up-navbar title="车辆列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder @leftClick="handleBackToDetail" />
    
    <view class="list-container">
      <!-- 搜索区域 -->
      <view class="search-section">
        <view class="search-bar">
          <up-search 
            v-model="searchKeyword"
            placeholder="搜索车牌号或车主姓名"
            @search="handleSearch"
            @clear="handleClear"
            :showAction="false"
            bgColor="#f5f5f5"
            :customStyle="{
              flex: 1,
              marginRight: '20rpx'
            }"
          />
          <up-button 
            type="primary"
            text="筛选"
            @click="showFilterModal = true"
            :customStyle="{
              width: '120rpx',
              height: '72rpx'
            }"
          />
        </view>
        
        <!-- 快速筛选 -->
        <view class="quick-filters">
          <view 
            class="filter-chip"
            :class="{ active: currentStatus === 'all' }"
            @click="handleStatusFilter('all')"
          >
            全部
          </view>
          <view 
            class="filter-chip"
            :class="{ active: currentStatus === 'completed' }"
            @click="handleStatusFilter('completed')"
          >
            已完成
          </view>
          <view 
            class="filter-chip"
            :class="{ active: currentStatus === 'pending' }"
            @click="handleStatusFilter('pending')"
          >
            待处理
          </view>
          <view 
            class="filter-chip"
            :class="{ active: currentStatus === 'unconfirmed' }"
            @click="handleStatusFilter('unconfirmed')"
          >
            未确认
          </view>
        </view>
      </view>
      
      <!-- 统计信息 -->
      <view class="stats-section">
        <view class="stats-card">
          <view class="stat-item">
            <text class="stat-number">{{ vehicleStats.total }}</text>
            <text class="stat-label">总数</text>
          </view>
          <view class="stat-item">
            <text class="stat-number completed">{{ vehicleStats.completed }}</text>
            <text class="stat-label">已完成</text>
          </view>
          <view class="stat-item">
            <text class="stat-number pending">{{ vehicleStats.pending }}</text>
            <text class="stat-label">待处理</text>
          </view>
          <view class="stat-item">
            <text class="stat-number unconfirmed">{{ vehicleStats.unconfirmed }}</text>
            <text class="stat-label">未确认</text>
          </view>
        </view>
      </view>
      
      <!-- 车辆列表 -->
      <view class="vehicle-list">
        <view class="vehicle-item" v-for="(item, index) in filteredVehicleList" :key="index"
          @click="handleVehicleClick(item)">
          <view class="vehicle-header">
            <view class="vehicle-plate-section">
              <text class="vehicle-plate">{{ item.plateNumber }}</text>
              <view class="vehicle-type">{{ getVehicleTypeText(item.vehicleType) }}</view>
            </view>
            <view class="vehicle-status" :class="getVehicleStatusClass(item.status)">
              {{ getVehicleStatusText(item.status) }}
            </view>
          </view>
          
          <view class="vehicle-content">
            <view class="vehicle-info">
              <view class="info-row">
                <text class="info-label">车主：</text>
                <text class="info-value">{{ item.ownerName }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">手机：</text>
                <text class="info-value">{{ item.phone }}</text>
              </view>
              <view class="info-row" v-if="item.parkingSpace">
                <text class="info-label">泊位：</text>
                <text class="info-value">{{ item.parkingSpace }}</text>
              </view>
            </view>
            
            <view class="vehicle-time">
              <text class="time-label">核验时间</text>
              <text class="time-value">{{ item.verifyTime || '待核验' }}</text>
            </view>
          </view>
          
          <view class="vehicle-result" v-if="item.result">
            <text class="result-label">核验结果：</text>
            <text class="result-value" :class="getResultClass(item.result)">{{ item.result }}</text>
          </view>
          
          <view class="vehicle-actions" v-if="item.status === 'pending'">
            <up-button 
              type="success"
              text="通过"
              size="small"
              @click.stop="handleApprove(item)"
              :customStyle="{
                marginRight: '20rpx',
                height: '60rpx'
              }"
            />
            <up-button 
              type="default"
              text="驳回"
              size="small"
              @click.stop="handleReject(item)"
              :customStyle="{
                height: '60rpx',
                color: '#f5222d',
                backgroundColor: '#fff',
                border: '1px solid #f5222d'
              }"
            />
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredVehicleList.length === 0">
        <text class="empty-text">暂无车辆数据</text>
      </view>
      
      <!-- 分页 -->
      <view class="pagination-section" v-if="filteredVehicleList.length > 0">
        <up-button 
          text="加载更多"
          type="primary"
          plain
          @click="loadMore"
          :loading="loading"
          :disabled="!hasMore"
          :customStyle="{
            width: '100%',
            height: '80rpx'
          }"
        />
      </view>
    </view>
    
    <!-- 筛选弹窗 -->
    <up-popup v-model:show="showFilterModal" mode="bottom" round="20">
      <view class="filter-modal">
        <view class="modal-header">
          <text class="modal-title">筛选条件</text>
          <up-icon name="close" @click="showFilterModal = false" />
        </view>
        
        <view class="filter-content">
          <view class="filter-group">
            <text class="group-title">车辆类型</text>
            <view class="filter-options">
              <view 
                class="filter-option"
                :class="{ active: filterOptions.vehicleType === 'all' }"
                @click="filterOptions.vehicleType = 'all'"
              >
                全部
              </view>
              <view 
                class="filter-option"
                :class="{ active: filterOptions.vehicleType === 'car' }"
                @click="filterOptions.vehicleType = 'car'"
              >
                小型车
              </view>
              <view 
                class="filter-option"
                :class="{ active: filterOptions.vehicleType === 'truck' }"
                @click="filterOptions.vehicleType = 'truck'"
              >
                货车
              </view>
            </view>
          </view>
          
          <view class="filter-group">
            <text class="group-title">核验结果</text>
            <view class="filter-options">
              <view 
                class="filter-option"
                :class="{ active: filterOptions.result === 'all' }"
                @click="filterOptions.result = 'all'"
              >
                全部
              </view>
              <view 
                class="filter-option"
                :class="{ active: filterOptions.result === 'pass' }"
                @click="filterOptions.result = 'pass'"
              >
                通过
              </view>
              <view 
                class="filter-option"
                :class="{ active: filterOptions.result === 'reject' }"
                @click="filterOptions.result = 'reject'"
              >
                驳回
              </view>
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <up-button 
            text="重置"
            type="info"
            plain
            @click="resetFilter"
            :customStyle="{
              flex: 1,
              marginRight: '20rpx',
              height: '80rpx'
            }"
          />
          <up-button 
            text="确定"
            type="primary"
            @click="applyFilter"
            :customStyle="{
              flex: 1,
              height: '80rpx'
            }"
          />
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const taskId = ref('')
const searchKeyword = ref('')
const currentStatus = ref('all')
const loading = ref(false)
const hasMore = ref(true)
const showFilterModal = ref(false)

// 筛选选项
const filterOptions = reactive({
  vehicleType: 'all',
  result: 'all'
})

// 车辆统计数据
const vehicleStats = reactive({
  total: 0,
  completed: 0,
  pending: 0,
  unconfirmed: 0
})

// 车辆列表数据
const vehicleList = ref([])
const currentPage = ref(1)
const pageSize = ref(20)

// 页面加载
onLoad((options) => {
  taskId.value = options.taskId || ''
  loadVehicleStats()
  loadVehicleList()
})

// 加载车辆统计
const loadVehicleStats = async () => {
  try {
    // TODO: 调用API获取车辆统计
    // const res = await getVehicleStats(taskId.value)
    
    // 模拟数据
    Object.assign(vehicleStats, {
      total: 150,
      completed: 120,
      pending: 25,
      unconfirmed: 5
    })
  } catch (error) {
    console.error('加载车辆统计失败:', error)
  }
}

// 加载车辆列表
const loadVehicleList = async (isLoadMore = false) => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    // TODO: 调用API获取车辆列表
    // const res = await getVehicleList({
    //   taskId: taskId.value,
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   keyword: searchKeyword.value,
    //   status: currentStatus.value,
    //   ...filterOptions
    // })
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        plateNumber: '京A12345',
        ownerName: '张三',
        phone: '138****1234',
        vehicleType: 'car',
        parkingSpace: 'A-001',
        status: 'completed',
        verifyTime: '2024-01-15 10:30:00',
        result: '核验通过'
      },
      {
        id: 2,
        plateNumber: '京B67890',
        ownerName: '李四',
        phone: '139****5678',
        vehicleType: 'truck',
        parkingSpace: 'B-002',
        status: 'pending',
        verifyTime: '',
        result: ''
      },
      {
        id: 3,
        plateNumber: '京C11111',
        ownerName: '王五',
        phone: '136****9999',
        vehicleType: 'car',
        parkingSpace: 'C-003',
        status: 'unconfirmed',
        verifyTime: '2024-01-15 11:00:00',
        result: '待确认'
      }
    ]
    
    if (isLoadMore) {
      vehicleList.value.push(...mockData)
    } else {
      vehicleList.value = mockData
    }
    
    // 模拟分页
    hasMore.value = currentPage.value < 3
    
  } catch (error) {
    console.error('加载车辆列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 过滤后的车辆列表
const filteredVehicleList = computed(() => {
  let list = vehicleList.value
  
  // 状态筛选
  if (currentStatus.value !== 'all') {
    list = list.filter(item => item.status === currentStatus.value)
  }
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    list = list.filter(item => 
      item.plateNumber.toLowerCase().includes(keyword) ||
      item.ownerName.toLowerCase().includes(keyword)
    )
  }
  
  // 车辆类型筛选
  if (filterOptions.vehicleType !== 'all') {
    list = list.filter(item => item.vehicleType === filterOptions.vehicleType)
  }
  
  // 核验结果筛选
  if (filterOptions.result !== 'all') {
    if (filterOptions.result === 'pass') {
      list = list.filter(item => item.result === '核验通过')
    } else if (filterOptions.result === 'reject') {
      list = list.filter(item => item.result === '核验驳回')
    }
  }
  
  return list
})

// 获取车辆类型文本
const getVehicleTypeText = (type: string) => {
  const typeMap = {
    'car': '小型车',
    'truck': '货车',
    'bus': '客车'
  }
  return typeMap[type] || '未知'
}

// 获取车辆状态样式类
const getVehicleStatusClass = (status: string) => {
  const statusMap = {
    'completed': 'status-completed',
    'pending': 'status-pending',
    'unconfirmed': 'status-unconfirmed'
  }
  return statusMap[status] || 'status-pending'
}

// 获取车辆状态文本
const getVehicleStatusText = (status: string) => {
  const statusMap = {
    'completed': '已完成',
    'pending': '待处理',
    'unconfirmed': '未确认'
  }
  return statusMap[status] || '未知'
}

// 获取结果样式类
const getResultClass = (result: string) => {
  if (result === '核验通过') return 'result-pass'
  if (result === '核验驳回') return 'result-reject'
  return 'result-pending'
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadVehicleList()
}

// 清空搜索
const handleClear = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  loadVehicleList()
}

// 状态筛选
const handleStatusFilter = (status: string) => {
  currentStatus.value = status
  currentPage.value = 1
  loadVehicleList()
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    currentPage.value++
    loadVehicleList(true)
  }
}

// 重置筛选
const resetFilter = () => {
  filterOptions.vehicleType = 'all'
  filterOptions.result = 'all'
}

// 应用筛选
const applyFilter = () => {
  showFilterModal.value = false
  currentPage.value = 1
  loadVehicleList()
}

// 车辆点击
const handleVehicleClick = (item: any) => {
  uni.navigateTo({
    url: `/pages/vehicle-internal-verify/vehicle-detail?taskId=${taskId.value}&vehicleId=${item.id}`
  })
}

// 通过处理
const handleApprove = async (item: any) => {
  try {
    // TODO: 调用API通过核验
    // await approveVehicle(item.id)
    
    uni.showToast({
      title: '操作成功',
      icon: 'success'
    })
    
    // 更新状态
    item.status = 'completed'
    item.result = '核验通过'
    item.verifyTime = new Date().toLocaleString()
    
  } catch (error) {
    console.error('通过操作失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    })
  }
}

// 驳回处理
const handleReject = async (item: any) => {
  uni.showModal({
    title: '驳回原因',
    editable: true,
    placeholderText: '请输入驳回原因',
    success: async (res) => {
      if (res.confirm) {
        try {
          // TODO: 调用API驳回核验
          // await rejectVehicle(item.id, res.content)
          
          uni.showToast({
            title: '操作成功',
            icon: 'success'
          })
          
          // 更新状态
          item.status = 'completed'
          item.result = '核验驳回'
          item.verifyTime = new Date().toLocaleString()
          
        } catch (error) {
          console.error('驳回操作失败:', error)
          uni.showToast({
            title: '操作失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

// 返回任务详情页面
const handleBackToDetail = () => {
  uni.redirectTo({
    url: `/pages/vehicle-internal-verify/detail?id=${taskId.value}`
  })
}
</script>

<style lang="scss" scoped>
.vehicle-list-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.list-container {
  padding: 20rpx;
}

.search-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.quick-filters {
  display: flex;
  gap: 16rpx;
}

.filter-chip {
  padding: 12rpx 24rpx;
  border-radius: 24rpx;
  font-size: 26rpx;
  color: #666666;
  background-color: #f5f5f5;
  transition: all 0.3s ease;
  
  &.active {
    background-color: #1890ff;
    color: #ffffff;
  }
}

.stats-section {
  margin-bottom: 20rpx;
}

.stats-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8rpx;
  
  &.completed {
    color: #52c41a;
  }
  
  &.pending {
    color: #fa8c16;
  }
  
  &.unconfirmed {
    color: #ff4d4f;
  }
}

.stat-label {
  font-size: 24rpx;
  color: #666666;
}

.vehicle-list {
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.vehicle-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.vehicle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.vehicle-plate-section {
  display: flex;
  align-items: center;
}

.vehicle-plate {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  margin-right: 16rpx;
}

.vehicle-type {
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
  background-color: #f0f0f0;
  color: #666666;
}

.vehicle-status {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
  
  &.status-completed {
    background-color: #f6ffed;
    color: #52c41a;
  }
  
  &.status-pending {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  &.status-unconfirmed {
    background-color: #fff1f0;
    color: #ff4d4f;
  }
}

.vehicle-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.vehicle-info {
  flex: 1;
}

.info-row {
  display: flex;
  margin-bottom: 8rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  font-size: 26rpx;
  color: #666666;
  min-width: 80rpx;
}

.info-value {
  font-size: 26rpx;
  color: #333333;
}

.vehicle-time {
  text-align: right;
}

.time-label {
  display: block;
  font-size: 22rpx;
  color: #999999;
  margin-bottom: 4rpx;
}

.time-value {
  font-size: 24rpx;
  color: #666666;
}

.vehicle-result {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.result-label {
  font-size: 26rpx;
  color: #666666;
  margin-right: 8rpx;
}

.result-value {
  font-size: 26rpx;
  
  &.result-pass {
    color: #52c41a;
  }
  
  &.result-reject {
    color: #ff4d4f;
  }
  
  &.result-pending {
    color: #fa8c16;
  }
}

.vehicle-actions {
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  text-align: center;
  padding: 100rpx 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

.pagination-section {
  margin-top: 20rpx;
}

.filter-modal {
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.filter-content {
  padding: 30rpx;
}

.filter-group {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.group-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 20rpx;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.filter-option {
  padding: 16rpx 32rpx;
  border-radius: 24rpx;
  font-size: 26rpx;
  color: #666666;
  background-color: #f5f5f5;
  transition: all 0.3s ease;
  
  &.active {
    background-color: #1890ff;
    color: #ffffff;
  }
}

.modal-footer {
  display: flex;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}
</style>